package com.jacky.iot.resources;

import org.eclipse.californium.core.CoapResource;
import org.eclipse.californium.core.Utils;
import org.eclipse.californium.core.coap.CoAP;
import org.eclipse.californium.core.coap.MediaTypeRegistry;
import org.eclipse.californium.core.coap.Request;
import org.eclipse.californium.core.server.resources.CoapExchange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SegPathResource extends CoapResource {

    private static final Logger log = LoggerFactory.getLogger(SegPathResource.class);

    // 客户端请 /seg1 /seg1/seg2 /seg1/seg2/seg3 都能请求到
    public SegPathResource() {
        this("seg1");
        SegPathResource seg2 = new SegPathResource("seg2");
        SegPathResource seg3 = new SegPathResource("seg3");
        add(seg2);
        seg2.add(seg3);
    }

    public SegPathResource(String name) {
        super(name);
        getAttributes().setTitle("Long path resource");
    }

    @Override
    public void handleGET(CoapExchange exchange) {
        Request request = exchange.advanced().getRequest();
        log.info("[segPath] req hexString:{}", Utils.toHexString(request.getBytes()));
        String payload = String.format("segPath Type: %d (%s)\nCode: %d (%s)\nMid: %d",
                request.getType().value,
                request.getType(),
                request.getCode().value,
                request.getCode(),
                request.getMID());
        exchange.respond(CoAP.ResponseCode.CONTENT, payload, MediaTypeRegistry.TEXT_PLAIN);
    }
}
